﻿using System;
using System.Windows.Forms;
using PluginInterface;
using System.Drawing;
using Qurihara;
using System.Collections;
using System.Xml;
using Qurihara.Anm;
using System.IO;
using OSC.NET;
using System.Threading;
using System.Net;
using Qurihara.QBasic;
using System.Text;
using System.Collections.Generic;
using Microsoft.Ink;
using System.Deployment.Application;
using System.Collections.Specialized;
using System.Web;
using System.Reflection;


namespace KotodamaPlugin.BoxDisplayPlugin
{
	/// <summary>
	/// Class1 の概要の説明です。
	/// </summary>
	public class BoxDisplayPlugin :IPlugin
    {

        public static string QRPrefix = "unryu.org:";

        #region OSC related

        private Qurihara.QBasic.TextEntryForm tef;
        //private void AskId(string defaultName)
        //{

        //    tef = new TextEntryForm("30秒経つと自動的に決定します。", "名前を入力してください。");
        //    tef.OutputText = defaultName;
        //    tef.Closed += new EventHandler(tef_Closed);
        //    tef.Show();
        //    Qurihara.Anm.WaitAnm wa = new WaitAnm(30000);
        //    wa.AnmFinishedHandler += new EventHandler(wa_AnmFinishedHandler);
        //    wa.Start();

        //}
        //private void wa_AnmFinishedHandler(object sender, EventArgs e)
        //{
        //    if (tef != null)
        //    {
        //        tef.Close();
        //    }
        //}


        //private void tef_Closed(object sender, EventArgs e)
        //{
        //    if (tef != null)
        //    {
        //        DialogResult dr = tef.DialogResult;
        //        if (dr == DialogResult.OK)
        //        {
        //            char[] trm = {'\n'};
        //            com.Name = tef.OutputText.TrimEnd(trm);
        //        }
        //        tef.Dispose();
        //        tef = null;

        //        //string str = QRPrefix + "ip=" + com.Ip + ",port=" + com.MPort.ToString() + ",id=" + com.Name;
        //        ////Bitmap bbm = QQR.GetQRImage(1, 4,
        //        ////    str);
        //        ////Bitmap bm = new Bitmap(bbm);
        //        ////Rectangle r = new Rectangle(120, 32, 400, 400);
        //        //////BitmapElement be = new BitmapElement(Host.Kotodama.Control,-1,r,bm);

        //        ////Host.Kotodama.Presentation.CurrentSlide.createBitmap(-1, r, bm);
        //        //////Host.Kotodama.Presentation.CurrentSlide.ForeGroundViewDependentElementList.Add(be);
        //        //Rectangle r3 = new Rectangle(0, 480, 640, 50);
        //        //Host.Kotodama.Presentation.CurrentSlide.createText(-1, r3, str, Color.Black, new Font("HG創英角ﾎﾟｯﾌﾟ体", 14));//("MS Gothic",14));

        //        //Rectangle r2 = new Rectangle(0, 400, 640, 50);
        //        string str = com.Name;
        //        ////TextElement te = new TextElement(Host.Kotodama.Control,-1,r2,str,Color.Black,new Font("MS Gothic",14));
        //        ////Host.Kotodama.Presentation.CurrentSlide.ForeGroundViewDependentElementList.Add(te);
        //        //Host.Kotodama.Presentation.CurrentSlide.createText(-1, r2, str, Color.Black, new Font("HG創英角ﾎﾟｯﾌﾟ体", 14));//("MS Gothic",14));
        //        //Host.Kotodama.Control.Invalidate();
        //        ////Host.Kotodama.Presentation.CurrentSlide.View.ViewRectangle = new Rectangle(0, 0, 640, 480);
        //        SetNameInWindow(str);
        //    }
        //}

        private void SetNameInWindow(string str)
        {
            Control c = (Control)Host.Kotodama.EnvironmentTable["Base.Form"];
            c.Text = " [" + str + "] " + c.Text + " ";
        }

        #endregion

        private MenuItem menuSubmitInk;
        private MenuItem menuSubmitPersonalInk;
        private MenuItem menuAutoScroll;
        private MenuItem menuDistribute;

        private MenuItem menuConfig;
        private MenuItem menuAutoSubmit;
        private MenuItem menuSendView;
        private MenuItem menuCanChangeAutoScroll;
        private MenuItem menuSendToAllInk;
        private MenuItem menuSendPersonalInk;
        private MenuItem menuReceivePersonalInk;

        private MenuItem menuOverview;
        private MenuItem menuSendLog;
        private MenuItem menuSnapOffset;

        private MenuItem sepa;
        private MenuItem filemenu;
        private MenuItem menuQuizBoard;
        private MenuItem menuQuizBoard12;
        private MenuItem menuQuizBoard20;
        private MenuItem menuQuizBoard24;
        private MenuItem menuQuizBoardAsk;

        private MenuItem menuReload;

        private PictureBox connectingPictureBox;

        private System.Windows.Forms.Timer timer;
        Qurihara.OSCCom.IComCore core;
        Qurihara.OSCCom.ComForDisplay com;

        private bool IsLanguage(string twoLetterISOLanguageName)
        {
            return (twoLetterISOLanguageName ==
                System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName);
        }

        public BoxDisplayPlugin()
		{
			//InitOSC();
            //com = new Qurihara.OSCCom.ComManager();

            menuAutoScroll = new MenuItem("AutoScroll");
            menuAutoScroll.Click += new EventHandler(menuAutoScroll_Click);

            menuConfig = new MenuItem(IsLanguage("en") ? "Config" : "設定");
            menuConfig.Popup += new EventHandler(menuConfig_Popup);

            menuDistribute = new MenuItem(IsLanguage("en") ? "Distribute" : "配布");
            menuDistribute.Click += new EventHandler(menuDistribute_Click);
            menuConfig.MenuItems.Add(menuDistribute);
            menuAutoSubmit = new MenuItem("AutoSubmit");
            menuAutoSubmit.Click += new EventHandler(menuAutoSubmit_Click);
            menuConfig.MenuItems.Add(menuAutoSubmit);
            menuSendView = new MenuItem("SendView");
            menuSendView.Click += new EventHandler(menuSendView_Click);
            menuConfig.MenuItems.Add(menuSendView);
            menuCanChangeAutoScroll = new MenuItem("CanChangeAutoScroll");
            menuCanChangeAutoScroll.Click += new EventHandler(menuCanChangeAutoScroll_Click);
            menuConfig.MenuItems.Add(menuCanChangeAutoScroll);
            menuSendToAllInk = new MenuItem("SendToAllInk");
            menuSendToAllInk.Click += new EventHandler(menuSendToAllInk_Click);
            menuConfig.MenuItems.Add(menuSendToAllInk);
            menuSendPersonalInk = new MenuItem("SendPersonalInk");
            menuSendPersonalInk.Click += new EventHandler(menuSendPersonalInk_Click);
            menuConfig.MenuItems.Add(menuSendPersonalInk);
            menuReceivePersonalInk = new MenuItem("ReceivePersonalInk");
            menuReceivePersonalInk.Click += new EventHandler(menuReceivePersonalInk_Click);
            menuConfig.MenuItems.Add(menuReceivePersonalInk);

            menuOverview = new MenuItem("Overview");
            menuOverview.Click += new EventHandler(menuOverview_Click);
            menuConfig.MenuItems.Add(menuOverview);
            menuSendLog = new MenuItem("SendLog");
            menuSendLog.Click += new EventHandler(menuSendLog_Click);
            menuConfig.MenuItems.Add(menuSendLog);
            menuSnapOffset = new MenuItem("SnapOffset1");
            menuSnapOffset.Click += new EventHandler(menuSnapOffset_Click);
            menuConfig.MenuItems.Add(menuSnapOffset);

            menuSubmitInk = new MenuItem("SubmitScreen");
            menuSubmitInk.Click += new EventHandler(menuSubmitInk_Click);
            //menuSubmitPersonalInk = new MenuItem("SubmitPersonal");
            //menuSubmitPersonalInk.Click += new EventHandler(menuSubmitPersonalInk_Click);
            menuConfig.MenuItems.Add(menuSubmitInk);

            sepa = new MenuItem();
            sepa.Text = "-";
            menuQuizBoard = new MenuItem(IsLanguage("en") ? "Quizboard" : "クイズボード");
            menuQuizBoard12 = new MenuItem(IsLanguage("en") ? "12 people" : "12人");
            menuQuizBoard12.Click += new EventHandler(menuQuizBoard12_Click);
            menuQuizBoard.MenuItems.Add(menuQuizBoard12);
            menuQuizBoard20 = new MenuItem(IsLanguage("en") ? "20 people" : "20人");
            menuQuizBoard20.Click += new EventHandler(menuQuizBoard20_Click);
            menuQuizBoard.MenuItems.Add(menuQuizBoard20);
            menuQuizBoard24 = new MenuItem(IsLanguage("en") ? "24 people" : "24人");
            menuQuizBoard24.Click += new EventHandler(menuQuizBoard24_Click);
            menuQuizBoard.MenuItems.Add(menuQuizBoard24);

            //menuQuizBoardAsk = new MenuItem(Util.IsPropertyTrue("Base.English") ? "custom" : "人数を指定");
            menuQuizBoardAsk = new MenuItem(IsLanguage("en") ? "custom" : "人数を指定");
            menuQuizBoardAsk.Click += new EventHandler(menuQuizBoardAsk_Click);
            menuQuizBoard.MenuItems.Add(menuQuizBoardAsk);

            //menuReload = new MenuItem("再描画");
            //menuReload.Click += new EventHandler(menuReload_Click);
        }

        //void menuReload_Click(object sender, EventArgs e)
        //{
        //    if (core is Qurihara.OSCCom.WebComCore)
        //    {
        //        firstConnected = false;
        //        connectingPictureBox.Enabled = true;
        //        connectingPictureBox.Visible = true;

        //        Qurihara.OSCCom.WebComCore.ResetUpdates();
        //    }
        //}

        void menuQuizBoardAsk_Click(object sender, EventArgs e)
        {
            AskNumber("16");
        }
        private void AskNumber(string defaultNum)
        {
            //tef = new TextEntryForm("人数確認", Util.IsPropertyTrue("Base.English") ? "How many people?" : "何人用のクイズボードを作成しますか？");
            tef = new TextEntryForm("人数確認", "何人用のクイズボードを作成しますか？ - How many people?");
            tef.OutputText = defaultNum;
            tef.Closed += new EventHandler(tef_Closed);
            tef.Show();
        }
        private void tef_Closed(object sender, EventArgs e)
        {
            string ans = "";
            if (tef != null)
            {
                DialogResult dr = tef.DialogResult;
                if (dr == DialogResult.OK)
                {
                    char[] trm = { '\n' };
                    ans = tef.OutputText.TrimEnd(trm);
                }
                tef.Dispose();
                tef = null;
            }

            int nAnswerer;
            if (int.TryParse(ans, out nAnswerer))
            {
                Assembly assm = Assembly.GetExecutingAssembly();
                Stream stream = assm.GetManifestResourceStream("BoxDisplayPlugin.flip.jpg");
                Bitmap bm = new Bitmap(Image.FromStream(stream));
                stream.Close();
                //Make
                ViewSnapList vsl = (ViewSnapList)Host.Kotodama.EnvironmentTable["CurrentViewSnapList"];
                int x, y;
                x = y = (int)Math.Ceiling(Math.Sqrt(nAnswerer));
                MakeQuizBoard(x, y,nAnswerer, bm, vsl);
                //Distribute
                DistributeAfterDialog();
            }
        }

        private void MakeQuizBoard(int xx, int yy,int number,Bitmap bm,ViewSnapList viewSnapList)
        {
            if (viewSnapList != null)
            {
                ViewSnap vs = new ViewSnap(
                    "overview",
                    new Rectangle(0,0,xx*1024,yy*768),
                    Host.Kotodama.Presentation.CurrentSlide.View);
                viewSnapList.Add(vs);
            }
            for (int y = 0; y < yy; y++)
            {
                for (int x = 0; x < xx; x++)
                {
                    Rectangle r = new Rectangle(
                        x * 1024,
                        y * 768,
                        1024,
                        768
                        );
                    Host.Kotodama.Presentation.CurrentSlide.createBitmap(-1, r, bm);
                    int index = y*xx+x+1;
                    string txt = index.ToString();
                    if (index > number) txt = "(" + txt + ")";
                    Host.Kotodama.Presentation.CurrentSlide.createText(-1, r, txt, Color.WhiteSmoke, new Font("",16F));

                    if (viewSnapList != null)
                    {
                        ViewSnap vs = new ViewSnap(
                            index.ToString(),
                            r,
                            Host.Kotodama.Presentation.CurrentSlide.View);
                        viewSnapList.Add(vs);
                    }
                }
            }
            Host.Kotodama.Control.Invalidate();
        }

        void menuQuizBoard20_Click(object sender, EventArgs e)
        {
            Assembly assm = Assembly.GetExecutingAssembly();
            Stream stream = assm.GetManifestResourceStream("BoxDisplayPlugin.quiz20overviewed.ks.xml");
            Host.Kotodama.Presentation.CurrentSlide.Load(stream, "");
            stream.Close();
            DistributeAfterDialog();
        }

        //        string pat = System.IO.Path.Combine(QBasic.Util.getPathWithoutFileName(Application.ExecutablePath),
        //"KOTODAMA_project");
        //        pat = System.IO.Path.Combine(pat, file);
        //        pat = System.IO.Path.Combine(pat, file + ".ks.xml");
        //        LoadStartPresen(pat);

        void menuQuizBoard24_Click(object sender, EventArgs e)
        {
            Assembly assm = Assembly.GetExecutingAssembly();
            Stream stream = assm.GetManifestResourceStream("BoxDisplayPlugin.quiz24overviewed.ks.xml");
            Host.Kotodama.Presentation.CurrentSlide.Load(stream, "");
            stream.Close();
            DistributeAfterDialog();
        }

        void menuQuizBoard12_Click(object sender, EventArgs e)
        {
            Assembly assm = Assembly.GetExecutingAssembly();
            Stream stream = assm.GetManifestResourceStream("BoxDisplayPlugin.quiz12overviewed.ks.xml");
            Host.Kotodama.Presentation.CurrentSlide.Load(stream, "");
            stream.Close();
            DistributeAfterDialog();
        }
        void DistributeAfterDialog()
        {
            if (DialogResult.OK == MessageBox.Show("資料を全員に配布します - Are you ready to distribute?","",MessageBoxButtons.OKCancel))
            {
                com.Distribute();
            }
        }

        void menuSnapOffset_Click(object sender, EventArgs e)
        {
            if (com._snapOffset == 0) com._snapOffset = 1;
            else com._snapOffset = 0;
        }

        void menuSendLog_Click(object sender, EventArgs e)
        {
            com._sendLog = !com._sendLog;
        }

        void menuOverview_Click(object sender, EventArgs e)
        {
            com._overview = !com._overview;
        }

        void menuConfig_Popup(object sender, EventArgs e)
        {
            menuAutoSubmit.Checked = com._sendInkImmediately;
            menuSendView.Checked = com._sendView;
            menuCanChangeAutoScroll.Checked = com._canChangeAutoScroll;
            menuSendToAllInk.Checked = com._sendToAllInk;
            menuSendPersonalInk.Checked = com._sendPersonalInk;
            menuReceivePersonalInk.Checked = com._recievePersonalInk;

            menuOverview.Checked = com._overview;
            menuSendLog.Checked = com._sendLog;
            menuSnapOffset.Checked = (com._snapOffset != 0) ? true:false;
        }

        void menuReceivePersonalInk_Click(object sender, EventArgs e)
        {
            com._recievePersonalInk = !com._recievePersonalInk;
        }

        void menuSendPersonalInk_Click(object sender, EventArgs e)
        {
            com._sendPersonalInk = !com._sendPersonalInk;
        }

        void menuSendToAllInk_Click(object sender, EventArgs e)
        {
            com._sendToAllInk = !com._sendToAllInk;
        }

        void menuCanChangeAutoScroll_Click(object sender, EventArgs e)
        {
            com._canChangeAutoScroll = !com._canChangeAutoScroll;
        }

        void menuSendView_Click(object sender, EventArgs e)
        {
            com._sendView = !com._sendView;
        }

        void menuDistribute_Click(object sender, EventArgs e)
        {
            com.Distribute();
        }

        void menuAutoSubmit_Click(object sender, EventArgs e)
        {
            com._sendInkImmediately = !com._sendInkImmediately;
        }

        void menuAutoScroll_Click(object sender, EventArgs e)
        {
            //com.EnableAutoScroll = !com.EnableAutoScroll;

            //if (com.EnableAutoScroll)
            //{
            //    menuAutoScroll.Text = "○AutoScroll";
            //}
            //else
            //{
            //    menuAutoScroll.Text = "×AutoScroll";
            //}
        }

        void menuSubmitInk_Click(object sender, EventArgs e)
        {
            List<StrokeElement> strokeList = new List<StrokeElement>();
            //foreach (FigureElement fe in Host.Kotodama.SelectedElementList)
            foreach(FigureElement fe in Host.Kotodama.Presentation.CurrentSlide.OnScreenElementList)
            {
                if (fe is StrokeElement)
                {
                    StrokeElement se = fe as StrokeElement;
                    strokeList.Add(se);//.Stroke);
                }
            }
            if (strokeList.Count > 0)
            {
                if (com._sendPersonalInk)
                    com.SendPersonalStroke(strokeList);
                else
                {
                    if (com._sendToAllInk)
                        com.SendToAllStroke(strokeList);
                }
                strokeList.Clear();
            }
            strokeList = null;
        }
        //void menuSubmitPersonalInk_Click(object sender, EventArgs e)
        //{
        //    List<Stroke> strokeList = new List<Stroke>();
        //    foreach (FigureElement fe in Host.Kotodama.SelectedElementList)
        //    {
        //        if (fe is StrokeElement)
        //        {
        //            StrokeElement se = fe as StrokeElement;
        //            strokeList.Add(se.Stroke);
        //        }
        //    }
        //    com.SendPersonalStroke(strokeList);
        //}

		#region IPlugin Members
		
		IPluginHost myPluginHost = null;
		string myPluginName = "BoxDisplay Plugin";
		string myPluginAuthor = "K.Qurihara";
		string myPluginDescription = "test plugin";
		string myPluginVersion = "1.0.0";

		public void Initialize()
		{
            if (ApplicationDeployment.IsNetworkDeployed)
            {
                NameValueCollection query = new NameValueCollection();
                string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
                query = HttpUtility.ParseQueryString(queryString);
                //managerなし連動
                string sync = query["sync"];
                //groupとname
                string group = query["group"];
                string name = query["name"];

                if (sync != null && sync == "true")
                {                    
                    core = new Qurihara.OSCCom.SyncWebComCore();
                }
                else
                {
                    core = new Qurihara.OSCCom.WebComCore();
                }
                if(name != null && name != "")
                    core.Name = name;
                if (group != null && group != "") 
                    ((Qurihara.OSCCom.WebComCore)core).GroupName = group;
            }
            else
            {
                core = new Qurihara.OSCCom.SyncWebComCore(); // TODO: ローカル起動したときにどうするかを決める
                //core = new Qurihara.OSCCom.TCPComCore();
                string gn = "";
                if (Qurihara.QBasic.Util.GetStringProperty("BoxDisplayPlugin.TestGroup", ref gn))
                {
                    ((Qurihara.OSCCom.WebComCore)core).GroupName = gn;
                }
            }
            com = new Qurihara.OSCCom.ComForDisplay(Host.Kotodama,core);

            //role
            bool ccas = com._canChangeAutoScroll;
            bool rpi = com._recievePersonalInk;
            bool sii = com._sendInkImmediately;
            bool spi = com._sendPersonalInk;
            bool stai = com._sendToAllInk;
            bool sv = com._sendView;
            bool ov = com._overview;
            int so = com._snapOffset;
            bool sl = com._sendLog;

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                NameValueCollection query = new NameValueCollection();
                string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
                query = HttpUtility.ParseQueryString(queryString);
                bool tm;
                if(bool.TryParse(query["ccas"],out tm)) ccas = tm;
                if(bool.TryParse(query["rpi"],out tm)) rpi = tm;
                if (bool.TryParse(query["sii"], out tm)) sii = tm;
                if (bool.TryParse(query["spi"], out tm)) spi = tm;
                if (bool.TryParse(query["stai"], out tm)) stai = tm;
                if (bool.TryParse(query["sv"], out tm)) sv = tm;
                if (bool.TryParse(query["ov"], out tm)) ov = tm;
                int tm2;
                if (int.TryParse(query["so"], out tm2)) so = tm2;

                //直接ロールを文字列指定していたらそれを優先させる。
                string role = query["role"];
                if (role.StartsWith("adjacent"))
                {
                    int _so = int.Parse(role.Substring(8)); // 8 = length of "adjacent"
                    sii = true; stai = true; spi = false; sv = false; ccas = true; ov = false; so = _so; sl = true; rpi = true;
                }
                else
                {
                    switch (role)
                    {
                        case "easy":
                            sii = true; stai = true; spi = false; sv = false; ccas = true; ov = false; so = 0; sl = false; rpi = false;
                            break;
                        case "student":
                            sii = true; stai = false; spi = true; sv = false; ccas = false; ov = false; so = 0; sl = false; rpi = false;
                            break;
                        case "audience":
                            sii = false; stai = false; spi = true; sv = false; ccas = false; ov = false; so = 0; sl = false; rpi = false;
                            break;
                        case "discussant":
                            sii = true; stai = true; spi = false; sv = false; ccas = true; ov = false; so = 0; sl = false; rpi = false;
                            break;
                        case "presenter":
                            sii = true; stai = true; spi = false; sv = true; ccas = true; ov = false; so = 0; sl = false; rpi = false;
                            break;
                        //case "manager":
                        //    break;
                        case "overview":
                            sii = true; stai = true; spi = false; sv = false; ccas = true; ov = true; so = 0; sl = true; rpi = true;
                            break;
                        //case "adjacent-2":
                        //    sii = true; stai = true; spi = false; sv = false; ccas = false; ov = false; so = -2; sl = true; rpi = true;
                        //    break;
                        //case "adjacent-1":
                        //    sii = true; stai = true; spi = false; sv = false; ccas = false; ov = false; so = -1; sl = true; rpi = true;
                        //    break;
                        //case "adjacent0":
                        //    sii = true; stai = true; spi = false; sv = false; ccas = false; ov = false; so = 0; sl = true; rpi = true;
                        //    break;
                        //case "adjacent1":
                        //    sii = true; stai = true; spi = false; sv = false; ccas = false; ov = false; so = 1; sl = true; rpi = true;
                        //    break;
                        //case "adjacent2":
                        //    sii = true; stai = true; spi = false; sv = false; ccas = false; ov = false; so = 2; sl = true; rpi = true;
                        //    break;
                        default:
                            break;
                    }
                }
                if (role != null && role != "")
                {
                    Control c = (Control)Host.Kotodama.EnvironmentTable["Base.Form"];
                    c.Text = " -" + role + "- " + c.Text;
                    //Host.Kotodama.Control.Text += " -" + role + "- ";
                }

                //send logは別格
                if (bool.TryParse(query["sl"], out tm)) sl = tm;

            }
            com._canChangeAutoScroll = ccas;
            com._recievePersonalInk = rpi;
            com._sendInkImmediately = sii;
            com._sendPersonalInk = spi;
            com._sendToAllInk = stai;
            com._sendView = sv;
            com._overview = ov;
            com._sendLog = sl;
            com._snapOffset = so;

            Menu.MenuItemCollection mic = (Menu.MenuItemCollection)Host.Kotodama.EnvironmentTable["Base.MenuItems"];
            //mic.Add(menuSubmitInk);
            mic.Add(menuAutoScroll);

            //filemenu = Qurihara.QBasic.DrawingUtil.FindByName(mic, Util.IsPropertyTrue("Base.English") ? "File" : "ファイル");
            filemenu = Qurihara.QBasic.DrawingUtil.FindByName(mic, "Menu");
            if (filemenu != null)
            {
                filemenu.MenuItems.Add(sepa);
                filemenu.MenuItems.Add(menuDistribute);
                filemenu.MenuItems.Add(menuConfig);
                filemenu.MenuItems.Add(menuQuizBoard);
                //filemenu.MenuItems.Add(menuReload);
            }

            connectingPictureBox = new PictureBox();
            Assembly assm = Assembly.GetExecutingAssembly();
            Stream stream = assm.GetManifestResourceStream("BoxDisplayPlugin.connecting.jpg");
            Image img = Image.FromStream(stream);
            stream.Close();

            connectingPictureBox.Image = img;
            connectingPictureBox.Size = img.Size;
            connectingPictureBox.Location = new Point(0, 0);
            Control cc = (Control)Host.Kotodama.EnvironmentTable["Base.Form"];
            connectingPictureBox.Parent = cc;
            Rectangle r = new Rectangle(connectingPictureBox.Location,connectingPictureBox.Size);
            Qurihara.QBasic.DrawingUtil.SynchronizeRectangleCenter(ref r, cc.ClientRectangle);
            connectingPictureBox.Location = r.Location;
            connectingPictureBox.Size = r.Size;
            connectingPictureBox.Enabled = false;
            connectingPictureBox.Visible = false;

            timer = new System.Windows.Forms.Timer();
            timer.Interval = 500;
            timer.Tick += new EventHandler(timer_Tick);
            timer.Enabled = true;
            timer.Start();
            //InitOSC();
            com.Initialize();//Host.Kotodama);
            //AskId(com.Name);
            SetNameInWindow(com.Name);

            //if (com._sendInkImmediately)
            //{
                //menuSubmitInk.Enabled = false;
                //menuSubmitInk.Visible = false;
            //}
		}

		void PluginInterface.IPlugin.Dispose()
		{
            //Disconnect();
            ////Host.Kotodama.Presentation.CurrentSlide.View.ViewChanged -=new EventHandler(View_ViewChanged);
            timer.Stop();
            timer.Enabled = false;
            timer.Dispose();
            com.Dispose();

            Menu.MenuItemCollection mic = (Menu.MenuItemCollection)Host.Kotodama.EnvironmentTable["Base.MenuItems"];
            //mic.Remove(menuSubmitInk);
            mic.Remove(menuAutoScroll);
            mic.Remove(menuDistribute);
            mic.Remove(menuConfig);

            filemenu.MenuItems.Remove(menuConfig);
            filemenu.MenuItems.Remove(menuDistribute);
            filemenu.MenuItems.Remove(sepa);
            filemenu.MenuItems.Remove(menuQuizBoard);
            filemenu.MenuItems.Remove(menuReload);

		}

		public string Description
		{
			get
			{
				// TODO:  Add ctlMain.Description getter implementation
				return myPluginDescription;
			}
		}

		public string Author
		{
			get
			{
				// TODO:  Add ctlMain.Author getter implementation
				return myPluginAuthor;
			}
		}

		public IPluginHost Host
		{
			get
			{
				// TODO:  Add ctlMain.Host getter implementation
				return myPluginHost;
			}
			set
			{
				myPluginHost = value;
			}
		}

		
		public string Name
		{
			get
			{
				// TODO:  Add ctlMain.Name getter implementation
				return myPluginName;
			}
		}
		

		public string Version
		{
			get
			{
				// TODO:  Add ctlMain.Version getter implementation
				return myPluginVersion;
			}
		}

		#endregion

        private bool firstConnected = false;
        void timer_Tick(object sender, EventArgs e)
        {
            Control c = (Control)Host.Kotodama.EnvironmentTable["Base.Form"];
            string t = c.Text;
            string [] ts = t.Split('@');
            string title = ts[0];
            string st = "";
            if (core != null && core.IsConnected)
            {
                firstConnected = true;
                connectingPictureBox.Visible = false;
                connectingPictureBox.Enabled = false;
            }
            if (core == null || !firstConnected)
            {
                Delegate d = (MethodInvoker)delegate()
                {
                    st = "@初期化中(initializing)";
                    c.Text = title + st;

                    connectingPictureBox.Enabled = true;
                    connectingPictureBox.Visible = true;
                };
                Host.Kotodama.Control.BeginInvoke(d);
            }else
            if (core.IsConnected)
            {
                //firstConnected = true;
                Delegate d = (MethodInvoker)delegate()
                {
                    st = "@接続中(online)";
                    c.Text = title + st;
                };
                Host.Kotodama.Control.BeginInvoke(d);
            }
            else
            {
                Delegate d = (MethodInvoker)delegate()
                {
                    st = "@非接続(offline)";
                    c.Text = title + st;
                };
                Host.Kotodama.Control.BeginInvoke(d);
            }
            if (com.EnableAutoScroll)
            {
                Delegate d = (MethodInvoker)delegate()
                {
                    menuAutoScroll.Text = "○AutoScroll";
                };
                Host.Kotodama.Control.BeginInvoke(d);
            }
            else
            {
                Delegate d = (MethodInvoker)delegate()
                {
                    menuAutoScroll.Text = "×AutoScroll";
                };
                Host.Kotodama.Control.BeginInvoke(d);
            }

        }
    }
}